<template>
  <div>
    <div style="display: flex;flex-direction:column;align-content: flex-start;">
      <div style="display: flex;flex-direction:row;align-content: flex-start;">
        <div style="margin: 5px 3px 5px 3px">
          <el-button type="primary"
                     size="mini"
                     @click="WebHttpSaveDialog('1')"
                     v-if="type!='signature'&&type!='preview'"
                     plain>提交文档
          </el-button>
        </div>
        <!--<div style="margin: 5px 3px 5px 3px">-->
          <!--<el-button type="primary"-->
                     <!--size="mini"-->
                     <!--@click="WebHttpSaveDialog('2')"-->
                     <!--v-if="type=='signature'"-->
                     <!--plain>提交文档-->
          <!--</el-button>-->
        <!--</div>-->
        <div style="margin: 5px 3px 5px 3px"
             v-if="WebHttpSaveDialogVisible">
          <el-form ref="fileNameForm"
                   :inline="true"
                   :model="fileNameForm"
                   label-width="80px"
                   :rules="fileNameFormRules"
                   size="mini">
            <el-form-item label="文件名称">
              <el-input v-model="fileNameForm.fileName"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div style="margin: 5px 3px 5px 3px"
             v-if="WebHttpSaveDialogVisible">
          <el-button type="primary"
                     @click="WebHttpSaveDialogCommit()"
                     size="mini">确 定</el-button>
          <el-button @click="WebHttpSaveDialogVisible = false"
                     size="mini">取 消</el-button>
        </div>
        <!--<div style="margin: 5px 3px 5px 3px">-->
        <!--<el-button type="primary"-->
        <!--size="mini"-->
        <!--@click="WebSignature()"-->
        <!--v-if="type=='signature'"-->
        <!--plain>添加签章-->
        <!--</el-button>-->
        <!--</div>-->
      </div>
      <div style="width: 900px;height: 900px">
        <table id="iTable"
               border=0>
          <tr>
            <td width="100%"
                height="100%"
                valign=top>
              <div id="WebOCX">
                <object classid="clsid:FF09E4FA-BFAA-486E-ACB4-86EB0AE875D5"
                        codebase="http://www.officectrl.com/weboffice/WebOffice.ocx#Version=2018,1,6,2"
                        id="WebOffice">
                  <param name="BorderStyle"
                         value="1">
                  <param name="Menubar"
                         value="0">
                  <param name="Titlebar"
                         value="1">
                  <param name="Toolbars"
                         value="1">
                </object>
              </div>
            </td>
          </tr>
        </table>
      </div>
    </div>

  </div>
</template>
<script>
  import * as WebCtrl from '../../assets/WebOffice'  //注意路径
  import { webOfficeCreateSpare } from "@/api/system";

  export default {
    data () {
      return {
        testvalue: '',
        access_token: null,
        type: '',
        fileId: null,
        fileName: '',
        saveType: '1',
        pdfIdSignature: null,
        planningTitle: '',
        listCode: '',
        WebHttpSaveFileName: '',
        fileNameForm: {
          fileName: null
        },
        WebHttpSaveDialogVisible: false,
        fileNameFormRules: {
          fileName: [
            { required: true, message: "请输入文件名称", trigger: "blur" }
          ]
        },
        fileextend:null

      }
    },
    mounted () {
      this.loadPage();
    },
    methods: {
      async loadPage () {
        await WebCtrl.LoadCtrl(WebOCX);
        await this.getSize();
        await this.getAccess_token();
        if (document.getElementById('WebOffice')) {
          let url;
          if (this.type == 'create') {
            //空白文档模板
            url =window.location.protocol+'//'+ window.location.host + process.env.VUE_APP_AXIOS_BASE_URL + '/planning/file/openDraft?fileName=webOfficeModel.doc&access_token=' + this.access_token;
            WebOffice.Open(url, true, 'Word.Document');

          } else if (this.type == 'check' || this.type == 'signature') {
            url = window.location.protocol+'//'+ window.location.host + process.env.VUE_APP_AXIOS_BASE_URL + '/planning/file/download/' + this.fileId
            WebOffice.Open(url, true, 'Word.Document');

          } else if(this.type == 'preview'){
            //关闭工具栏
            WebOffice.Toolbars = false;
            //关闭标题栏
            WebOffice.Titlebar = false;
            //关闭菜单栏
            WebOffice.MenuBars = false;
            //阅读视图
            WebOffice.ShowView(7)
            url = window.location.protocol+'//'+ window.location.host + process.env.VUE_APP_AXIOS_BASE_URL + '/planning/file/download/' + this.fileId

            switch (this.fileextend) {
              case 'WORD':WebOffice.Open(url, true, 'Word.Document');break
              case 'EXCEL':WebOffice.Open(url, true, 'Excel.Sheet');break
              // case 'PPT':WebOffice.Open(url, true, 'PowerPoint.Show');break
            }
          }


          let day = new Date();
          WebOffice.SetFieldValue('day2', day.getDate(), '::SETMARK::');
          WebOffice.SetFieldValue('month2', day.getMonth() + 1, '::SETMARK::');
          if (this.type == 'create') {
            WebOffice.SetFieldValue('title1', this.planningTitle, '::SETMARK::');
          }
          WebOffice.SetFieldValue('year1', day.getFullYear(), '::SETMARK::');
          WebOffice.SetFieldValue('year2', day.getFullYear(), '::SETMARK::');

          WebOffice.SetFieldValue('name1', '省政府办公厅', '::SETMARK::');
          WebOffice.SetFieldValue('code1', this.listCode, '::SETMARK::');
        }
      },
      getAccess_token () {
        let href = decodeURI(window.location.href); //获取url中"?"符后的字串
        let requestObj = this.getRequest(href);
        this.access_token = requestObj.access_token;
        this.type = requestObj.type;
        this.fileId = requestObj.fileId;
        this.fileName = requestObj.fileName;
        this.fileextend = requestObj.fileextend;
        this.pdfIdSignature = requestObj.pdfIdSignature;
        if (this.type == 'create'||this.type == 'check') {
          this.planningTitle = requestObj.planningTitle;
          this.listCode = requestObj.listCode;
        }
        this.fileNameForm.fileName = requestObj.fileName;
      },
      getRequest (url) {
        let theRequest = {};
        if (url.indexOf("?") != -1) {
          let str = url.substr(0);
          let strtemp = str.split('?')[1];
          let strs = strtemp.split("&");
          for (let i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
          }
        }
        return theRequest;
      },
      WebSignature () {
        // let url = process.env.VUE_APP_FULL_PUBLIC_PATH + '/check.gif';
        // WebCtrl.WebSignature(url)
      },
      async WebHttpSaveDialog (saveType) {
        this.saveType = await saveType;
        this.WebHttpSaveDialogCommit()
        // this.WebHttpSaveDialogVisible = true
      },
      async WebHttpSaveDialogCommit () {
        this.fileNameForm.fileName = await this.planningTitle
        if (this.fileNameForm.fileName == '' || this.fileNameForm.fileName == null) {
          alert('请输入文件名称!');
          return
        }else {
          let filenameTemp;
          filenameTemp =await this.fileNameForm.fileName;

          this.WebHttpSave(filenameTemp)
        }
        // this.$refs.fileNameForm.validate(valid => {
        //   if (valid) {
        //     let filenameTemp;
        //     filenameTemp = this.fileNameForm.fileName;
        //
        //     this.WebHttpSave(filenameTemp)
        //   }
        // })
      },
      WebHttpSave (fileName) {
        //对fileName进行转码
        let filenameTemp;
        filenameTemp = fileName + '.doc';
        let encodeFileName = encodeURI(filenameTemp);
        WebOffice.HttpInit();
        WebOffice.HttpAddPostString('fileName', encodeFileName);
        WebOffice.HttpAddPostString('fileId', this.fileId);
        WebOffice.HttpAddPostCurrFile('111', '');

        //后台保存文件路径
        let url = window.location.protocol+'//'+ window.location.host + process.env.VUE_APP_AXIOS_BASE_URL + '/planning/file/upload?access_token=' + this.access_token + '&fileType=' + '4';
        let delin;
        if (this.saveType == '1') {
          delin = confirm('你确定要提交文档:[' + this.fileNameForm.fileName + '.doc]' + '并关闭此窗口吗？');
        } else if (this.saveType == '2') {
          delin = confirm('你确定要提交文档:[' + this.fileNameForm.fileName + '.PDF]' + '并关闭此窗口吗？');
        }
        if (delin) {
          if (this.saveType == '1') {
            let strResults = WebOffice.HttpPost(url);
            let str = JSON.stringify(strResults);
            if (str != '') {
              window.close()
            }
          } else if (this.saveType == '2') {
            let pdfFilename = fileName + '.PDF';
            let urltemp = window.location.protocol+'//'
              + window.location.host + process.env.VUE_APP_AXIOS_BASE_URL
              + '/planning/file/upload?access_token='
              + this.access_token + '&fileType=' + '4'
              + '&fileName=' + pdfFilename
              + '&fileId=' + this.pdfIdSignature;

            //首先在本地缓冲区生成PDF文件
            let tempPath = WebOffice.TempFilePath;
            let pdfile = tempPath + 'temp' + '.PDF';
            //PDF生成方式一：
            WebOffice.ActiveDocument.saveas(pdfile, 17);
            WebOffice.WebUploadFile(urltemp, pdfile);

            let strResults = WebOffice.HttpPost(url);
            let str = JSON.stringify(strResults);
            alert('已保存完成，请查看是否成功!');
            if (str != '') {
              window.close()
            }
          }

        }


      },
      WebPdfRemote () {
        try {
          if (isOpen) {
            let strPdfSaveUrl = '';
            let pfile = "temp";
            //首先在本地缓冲区生成PDF文件
            let tempPath = WebOffice.TempFilePath;
            let pdfile = tempPath + pfile + '.PDF';
            //PDF生成方式一：
            WebOffice.ActiveDocument.saveas(pdfile, 17);
            //PDF生成方式二：
            //WebOffice.ActiveDocument.ExportAsFixedFormat(pdfile,17);
            //其次上传 pdf文件到服务器，后清空缓冲区中的文档
            //WebOffice.WebSaveAsPDF(pdfile,strPdfSaveUrl);
            WebOffice.WebUploadFile(strPdfSaveUrl, pdfile);
            alert('已保存完成，请查看是否成功!');
          }
        }
        catch (e) {
          alert('发生错误！可能原因有：1、您本地的Office版本过低不支持将WORD文件转为PDF文件,请安装OFFICE2010以上版本！ \n 2、远程保存时服务器端发生错误！');
        }
      },
      getSize () {
        //获取窗口宽度
        let winWidth = 0;
        if (window.innerWidth) {
          winWidth = window.innerWidth;
        } else if ((document.body) && (document.body.clientWidth)) {
          winWidth = document.body.clientWidth;
        }
        //获取窗口高度
        let winHeight = 0;
        if (window.innerHeight) {
          winHeight = window.innerHeight;
        } else if ((document.body) && (document.body.clientHeight)) {
          winHeight = document.body.clientHeight;
        }
        //通过深入Document内部对body进行检测，获取窗口大小
        if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
          winHeight = document.documentElement.clientHeight;
          winWidth = document.documentElement.clientWidth;
        }
        let iTable = document.getElementById('iTable');
        let iTabletop = this.getAbsoluteTop(iTable) + 25;//25为窗体的标题栏高度
        let iTableleft = this.getAbsoluteLeft(iTable);
        if (winHeight > (iTabletop) && winWidth > iTableleft) {
          document.getElementById('iTable').height = winHeight - iTabletop;
          document.getElementById('iTable').width = winWidth - iTableleft;
        }
      }
      ,
      getAbsoluteTop (ob) {
        if (!ob) {
          return null;
        }
        let mendingOb = ob;
        let mendingTop = mendingOb.offsetTop;
        while (mendingOb != null && mendingOb.offsetParent != null && mendingOb.offsetParent.tagName != "BODY") {
          mendingTop += mendingOb.offsetParent.offsetTop;
          mendingOb = mendingOb.offsetParent;
        }
        return mendingTop;
      }
      ,
      getAbsoluteLeft (ob) {
        if (!ob) {
          return null;
        }
        let mendingOb = ob;
        let mendingLeft = mendingOb.offsetLeft;
        while (mendingOb != null && mendingOb.offsetParent != null && mendingOb.offsetParent.tagName != "BODY") {
          mendingLeft += mendingOb.offsetParent.offsetLeft;
          mendingOb = mendingOb.offsetParent;
        }
        return mendingLeft;
      }
    }
  }
</script>
<style scoped>
  @import url("../../assets/css/common.css");
  body,
  a {
    font-size: 14px;
  }
</style>
